package com.ruoyi.common.utils.ip

import com.alibaba.fastjson2.JSON
import com.ruoyi.common.config.RuoYiConfig
import com.ruoyi.common.constant.Constants
import com.ruoyi.common.utils.MyStringUtils
import com.ruoyi.common.utils.http.HttpUtils
import org.slf4j.LoggerFactory

/**
 * 获取地址类
 *
 * @author ruoyi
 */
object AddressUtils {
    private val log = LoggerFactory.getLogger(AddressUtils::class.java)

    // IP地址查询
    private const val IP_URL = "http://whois.pconline.com.cn/ipJson.jsp"

    // 未知地址
    private const val UNKNOWN = "XX XX"
    @JvmStatic
    fun getRealAddressByIP(ip: String): String {
        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return "内网IP"
        }
        if (RuoYiConfig.isAddressEnabled) {
            try {
                val rspStr = HttpUtils.sendGet(IP_URL, "ip=$ip&json=true", Constants.GBK)
                if (MyStringUtils.isEmpty(rspStr)) {
                    log.error("获取地理位置异常 {}", ip)
                    return UNKNOWN
                }
                val obj = JSON.parseObject(rspStr)
                val region = obj.getString("pro")
                val city = obj.getString("city")
                return String.format("%s %s", region, city)
            } catch (e: Exception) {
                log.error("获取地理位置异常 {}", ip)
            }
        }
        return UNKNOWN
    }
}
